package com.zc.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
/**
 * 获取位置工具类
 * 		权限    
 * 			<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
 *     		<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
 *   		<uses-permission android:name="android.permission.INTERNET"/> 
 */
public class LocationUtil {
	public static final String TAG ="LOCATIONUTIL";
	
	public static Location getLocation(Context context){
		Location local = null;
		LocationManager localManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
		List<String> providers = localManager.getAllProviders();
		if (providers != null && providers.size()>0) {
			for (String string : providers) {
				if (string.equals(LocationManager.GPS_PROVIDER) || string.equals(LocationManager.NETWORK_PROVIDER)) {
					if(!localManager.isProviderEnabled(string)){
						try {
							System.out.println("begin to open the gps");
							Settings.Secure.setLocationProviderEnabled(
					                context.getContentResolver(),
					                LocationManager.GPS_PROVIDER,
					                true);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					local = localManager.getLastKnownLocation(string);
				} else if (string.equals(LocationManager.PASSIVE_PROVIDER) && localManager.isProviderEnabled(string)) {
					TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
					switch (telManager.getSimState()) {
					case TelephonyManager.SIM_STATE_ABSENT://无卡
					case TelephonyManager.SIM_STATE_UNKNOWN://未知
					case TelephonyManager.SIM_STATE_NETWORK_LOCKED://需要networ解锁
					case TelephonyManager.SIM_STATE_PIN_REQUIRED://需要pin解锁
					case TelephonyManager.SIM_STATE_PUK_REQUIRED://需要puk解锁
						break;
					case TelephonyManager.SIM_STATE_READY://正常状态
//						local = getLocalByBase(context);
//						getLocal();
					default:
						break;
					}
				}
				if (local != null) {
					break;
				}
			}
		}
		return local;
	}
	/**
	 * 获取地址所在的城市名称
	 * @param context
	 * @param location
	 * @return
	 */
	public static String getCityNameByLocation(Context context, Location location){
		if (location == null) return "获取地址失败";
		double lat = location.getLatitude();
		double lon = location.getLongitude();
		String urlStr = String.format("http://ditu.google.cn/maps/geo?key=abcdef&q="+lat+","+lon);
		InputStream is = null;
		HttpURLConnection conn = null;
		try {
			URL url = new URL(urlStr);
			conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setReadTimeout(10 * 1000);
			conn.setConnectTimeout(6 * 1000);
			conn.setRequestProperty("Content-Type", "text/json;charset=utf-8");
			conn.setRequestProperty("Connection", "keep-alive");
			conn.connect();
			if (200 == conn.getResponseCode()) {
				is = conn.getInputStream();
				ByteArrayOutputStream os = new ByteArrayOutputStream();
				byte[] buffer = new byte[2048];
				int len = 0;
				while((len = is.read(buffer)) != -1){
					os.write(buffer,0,len);
				}
				String result = new String(os.toByteArray());
				if(result!=null){
					try {
						JSONObject obj = new JSONObject(result);
						JSONArray name = obj.getJSONArray("Placemark");
						JSONObject obj1 = name.getJSONObject(0);
						JSONObject obj2 = obj1.getJSONObject("AddressDetails");
						JSONObject obj3 = obj2.getJSONObject("Country");
						JSONObject obj4 = obj3.getJSONObject("AdministrativeArea");
						JSONObject obj5 = obj4.getJSONObject("Locality");
						String locationName = obj5.getString("LocalityName");
						return locationName;
					} catch (JSONException e) {
						e.printStackTrace();
						return "ERROR:地址解释失败";
					}
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				conn.disconnect();
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "ERROR:获取地址失败";
	}
	

}

